package com.ruoyi.system.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.CommonConstant;
import com.ruoyi.common.core.domain.entity.admin.AdminCropDB;
import com.ruoyi.common.core.domain.entity.admin.AdminPlotCropRelDB;
import com.ruoyi.common.core.domain.entity.admin.AdminPlotDB;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.global.CustomException;
import com.ruoyi.common.utils.sql.MyPageUtils;
import com.ruoyi.common.vo.PlotCropShowVO;
import com.ruoyi.system.mapper.admin.AdminCropVarietiesMapper;
import com.ruoyi.system.mapper.admin.AdminPlotMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminPlotService {

    @Resource
    private AdminPlotMapper adminPlotDBMapper;

    @Resource
    private AdminCropVarietiesMapper adminCropVarietiesMapper;

    @Resource
    private AdminPlotCropRelService adminPlotCropRelService;

    /**
     * 查询后台-菜园
     *
     * @param id 后台-菜园主键
     * @return 后台-菜园
     */
    public AdminPlotDB selectAdminPlotDBById(Long id) {
        return adminPlotDBMapper.selectById(id);
    }

    /**
     * 查询后台-菜园列表
     *
     * @param adminPlotDB 后台-菜园
     * @return 后台-菜园
     */
    public TableDataInfo selectAdminPlotDBList(AdminPlotDB adminPlotDB) {

        LambdaQueryWrapper<AdminPlotDB> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(adminPlotDB.getSerialNumber()), AdminPlotDB::getSerialNumber, adminPlotDB.getSerialNumber());
        wrapper.eq(ObjectUtils.isNotEmpty(adminPlotDB.getCategory()), AdminPlotDB::getCategory, adminPlotDB.getCategory());
        wrapper.like(ObjectUtils.isNotEmpty(adminPlotDB.getExternalName()), AdminPlotDB::getExternalName, adminPlotDB.getExternalName());
        wrapper.eq(ObjectUtils.isNotEmpty(adminPlotDB.getRentalStatus()), AdminPlotDB::getRentalStatus, adminPlotDB.getRentalStatus());
        wrapper.eq(ObjectUtils.isNotEmpty(adminPlotDB.getIsActive()), AdminPlotDB::getIsActive, adminPlotDB.getIsActive());

        wrapper.orderByDesc(AdminPlotDB::getId);
        Page<AdminPlotDB> pageParam = MyPageUtils.handlePageParam();
        Page<AdminPlotDB> adminPlotDBPage = adminPlotDBMapper.selectPage(pageParam, wrapper);
        return TableDataInfo.covert(adminPlotDBPage);


    }

    /**
     * 新增后台-菜园
     *
     * @param adminPlotDB 后台-菜园
     * @return 结果
     */
    public int insertAdminPlotDB(AdminPlotDB adminPlotDB) {
        return adminPlotDBMapper.insert(adminPlotDB);
    }

    /**
     * 修改后台-菜园
     *
     * @param adminPlotDB 后台-菜园
     * @return 结果
     */
    public int updateAdminPlotDB(AdminPlotDB adminPlotDB) {
        return adminPlotDBMapper.updateById(adminPlotDB);
    }


    // 菜园添加种植物
    public void addPlant(Long plotId, List<Long> cropIds, Date plantingTime) {
        AdminPlotCropRelDB relDB = new AdminPlotCropRelDB();
        relDB.setPlotId(plotId);
        relDB.setCropIds(cropIds);
        relDB.setPlantingTime(plantingTime);

        adminPlotCropRelService.addRel(relDB);
    }

    public List<PlotCropShowVO> findCropList(Long plotId) {
        ArrayList<PlotCropShowVO> resultList = new ArrayList<>();
        List<AdminPlotCropRelDB> list = adminPlotCropRelService.findCropListByPlotId(plotId);
        if (ObjectUtils.isEmpty(list)) {
            return resultList;
        }

        // 获取所有果蔬品种id
        List<Long> ids = list.stream().map(AdminPlotCropRelDB::getCropId).collect(Collectors.toList());
        // 查询数据库
        List<AdminCropDB> cropDBList = adminCropVarietiesMapper.selectBatchIds(ids);
        // cropDBList 转为map
        Map<Long, AdminCropDB> cropDBMap = cropDBList.stream().collect(Collectors.toMap(AdminCropDB::getId, v -> v, (e1, e2) -> e2));

        for (AdminPlotCropRelDB item : list){
            PlotCropShowVO plotCropShowVO = new PlotCropShowVO();
            Long cropId = item.getCropId();
            AdminCropDB adminCropDB = cropDBMap.get(cropId);
            if (ObjectUtils.isEmpty(adminCropDB)){
                continue;
            }
            plotCropShowVO.setCropId(adminCropDB.getId());
            plotCropShowVO.setCropName(adminCropDB.getCropName());
            plotCropShowVO.setEstimatedHarvestTime(item.getEstimatedHarvestTime());

            resultList.add(plotCropShowVO);
        }


        return resultList;
    }

    public List<AdminPlotDB> findAll() {
        // 查询所有，状态正常，未出租
        LambdaQueryWrapper<AdminPlotDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminPlotDB::getIsActive, CommonConstant.CONSTANT_NUM.ONE);
        queryWrapper.eq(AdminPlotDB::getRentalStatus, "未出租");
        queryWrapper.orderByAsc(AdminPlotDB::getId);
        List<AdminPlotDB> adminPlotDBS = adminPlotDBMapper.selectList(queryWrapper);
        if (ObjectUtils.isEmpty(adminPlotDBS)){
            throw new CustomException("目前菜地均已出租");
        }
        // TODO 再组装每个菜地的意向人数（近X个月的意向）
        return adminPlotDBS;
    }


//    /**
//     * 批量删除后台-菜园
//     *
//     * @param ids 需要删除的后台-菜园主键
//     * @return 结果
//     */
//    public int deleteAdminPlotDBByIds(Long[] ids)
//    {
//        return adminPlotDBMapper.deleteAdminPlotDBByIds(ids);
//    }

//    /**
//     * 删除后台-菜园信息
//     *
//     * @param id 后台-菜园主键
//     * @return 结果
//     */
//    public int deleteAdminPlotDBById(Long id)
//    {
//        return adminPlotDBMapper.deleteAdminPlotDBById(id);
//    }
//

}
